package com.imooc.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author sea_son
 * @date 2018/7/13 10:09
 * 海客森：www.hikson.com
 * QQ：1099161566@qq.com
 */
@Service
public class SeckillService {

    @Autowired
    private RedisLock redisLock;
    
    private static long TIMEOUT = (long) 20*60*1000;

    /**
     * 加锁、解锁
     * @param productId
     */
    public void orderProductMockDiffUser(String productId) {
        Stock stock = new Stock();
        //加锁
        long time = System.currentTimeMillis()+TIMEOUT;
        if (!redisLock.lock(productId, String.valueOf(time))) {
            throw new RuntimeException("人太多啦，换个姿势~");//异常一般自定义
        }
        //1. 查询该商品库存，为0则活动结束。
        int stockNum = stock.get(productId);
        if (stockNum == 0) {
            throw new RuntimeException("抢完啦~");
        }
        //2.下单（模拟不同的用户）
        //3.减库存
        stockNum = stockNum-1;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stock.put(productId, stock);
        //解锁
        redisLock.unlock(productId,String.valueOf(time));
    }
}

class Stock {
    //实际上是数据库查询的
    private int stockNum=10;
    public int get(String productId) {
        return this.stockNum;
    }
    public void put(String productId, Stock stock) {
    }
}